from flask import Flask, request, Response, stream_with_context
import aiohttp
import asyncio
import gzip
from io import BytesIO

app = Flask(__name__)

TELEGRAPH_URL = "https://api.openai.com"

@app.route("/", defaults={"path": ""}, methods=["GET", "POST", "PUT", "DELETE"])
@app.route("/<path:path>", methods=["GET", "POST", "PUT", "DELETE"])
async def proxy(path):
    global TELEGRAPH_URL
    parts = path.split("/")
    new_path = "/" + "/".join(parts[1:])
    url = TELEGRAPH_URL + "/" + new_path
    headers = dict(request.headers)
    headers["Host"] = TELEGRAPH_URL.replace("https://", "")
    headers["Access-Control-Allow-Origin"] = headers.get("Access-Control-Allow-Origin") or "*"

    async with aiohttp.ClientSession() as session:
        async with session.request(
            method=request.method,
            url=url,
            headers=headers,
            data=request.get_data(),
            cookies=request.cookies,
            allow_redirects=False,
        ) as response:
            def generate():
                if response.headers.get('Content-Encoding') == 'gzip':
                    buffer = BytesIO()
                    async for chunk in response.content.iter_chunked(1024):
                        if chunk:
                            buffer.write(chunk)
                    buffer.seek(0)
                    with gzip.GzipFile(fileobj=buffer, mode='rb') as f:
                        yield f.read()
                else:
                    async for chunk in response.content.iter_chunked(1024):
                        if chunk:
                            yield chunk

            excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
            headers = [(name, value) for (name, value) in response.headers.items()
                       if name.lower() not in excluded_headers]

            headers = {name: value for name, value in headers}

            if 'Content-Encoding' in headers:
                del headers['Content-Encoding']

            return Response(stream_with_context(generate()), response.status, headers)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9595, threaded=True)